package com.ksfzhaohui.nio.channels;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class Marketing {

	private static final String TXT_NAME = "gatherTest.txt";

	private static final int reqs = 10;

	public static void main(String[] args) throws Exception {
		FileOutputStream fos = new FileOutputStream(TXT_NAME);
		GatheringByteChannel gatherChannel = fos.getChannel();

		ByteBuffer bf[] = utterBs(reqs);
		while (gatherChannel.write(bf) > 0) {

		}

		fos.close();
	}

	public static String col1[] = { "a1", "a2", "a3", "a4", "a5", "a6", "a7",
			"a8", "a9" };

	public static String col2[] = { "b1", "b2", "b3", "b4", "b5", "b6", "b7",
			"b8", "b9" };

	public static String col3[] = { "c1", "c2", "c3", "c4", "c5", "c6", "c7",
			"c8", "c9" };

	private static final String newline = System.getProperty("line.separator");

	private static ByteBuffer[] utterBs(int howMany) throws Exception {
		List<ByteBuffer> list = new LinkedList<ByteBuffer>();
		for (int i = 0; i < howMany; i++) {
			list.add(pickRandom(col1, " "));
			list.add(pickRandom(col2, " "));
			list.add(pickRandom(col3, newline));
		}

		ByteBuffer buffa[] = new ByteBuffer[list.size()];
		list.toArray(buffa);

		return buffa;
	}

	private static Random rand = new Random();

	private static ByteBuffer pickRandom(String strings[], String suffix)
			throws Exception {
		String string = strings[rand.nextInt(strings.length)];
		int total = string.length() + suffix.length();
		ByteBuffer buff = ByteBuffer.allocate(total);
		buff.put(string.getBytes("US-ASCII"));
		buff.put(suffix.getBytes("US-ASCII"));
		buff.flip();
		return buff;
	}
}
